package day01;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/11 15:16
 * 力扣 102
 */
public class TreeNodePractice {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(
                        new TreeNode(4),
                        2,
                        new TreeNode(5)
                ),
                1,
                new TreeNode(
                        new TreeNode(6),
                        3,
                        new TreeNode(7)
                )
        );

        List<List<Integer>> lists = levelOrder(root);
        System.out.println(lists);


    }

    //  二叉树层序遍历
    public static List<List<Integer>> levelOrder(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> lists = new ArrayList<>();
        queue.offer(root);
        int c1 = 1;
        while(!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int c2 = 0;
            for (int i = 0; i < c1; i++) {
                TreeNode n = queue.poll();
                list.add(n.val);
                if (n.left != null) {
                    queue.offer(n.left);
                    c2++;
                }
                if (n.right != null) {
                    queue.offer(n.right);
                    c2++;
                }
            }
            lists.add(list);
            c1 = c2;
        }
        return lists;
    }
}
